<?php

namespace app\admin\controller\room;

use app\common\controller\Backend;
use app\common\library\Jcc;
use app\common\model\game\Groups;
use app\common\model\game\Modes;
use app\common\model\GoldLog;
use app\common\model\MoneyLog;
use app\common\model\User;
use app\common\model\user\Bindgame;
use think\Cache;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 房间人员管理
 *
 * @icon fa fa-circle-o
 */
class Users extends Backend
{

    /**
     * Users模型对象
     * @var \app\common\model\room\Users
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\room\Users;
        $this->view->assign("room_id", $this->request->param("room_id", 0));
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['lists', 'user', 'bindgame'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('lists')->visible(['id']);
                $row->getRelation('user')->visible(['nickname', 'mobile']);
                $row->getRelation('bindgame')->visible(['game_number', 'game_nickname', 'game_avatar']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function index_extend()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);
                $custom = (array)$this->request->request("custom/a");

                $list = $this->model->with(['bindgame'])
                    ->where($custom)
                    ->select();

                $result = [];
                foreach ($list as $value) {
                    $array = [
                        'pid' => 0,
                        'id' => $value['user_id'],
                        'name' => $value['bindgame']['game_nickname']
                    ];
                    $result['list'][] = $array;
                }
                $result['total'] = $this->model->with(['bindgame'])
                    ->where($custom)
                    ->count();
                return json($result);
            }
        }

        return false;
    }


    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $room_id = $this->request->param("room_id", 0);
        $room = \app\common\model\room\Lists::get($room_id);
        if (!$room) {
            $this->error("房间有误");
        }

        if (in_array($room['status'], [2, 3])) {
            $this->error("当前房间已结束");
        }

        $mode = Modes::get($room['modes_id']);
        $num = $this->model->where('room_id', $room_id)->count();
        if ($num >= $mode['capacity_num']) {
            $this->error("当前模式人数超限");
        }

        $user_bind = Bindgame::where('id', $params['game_id'])->find();
        $user_id = $user_bind['user_id'];

        $group_id = Groups::where([
            'game_id' => $room['game_id'], 'subarea_id' => $room['subarea_id'],
            'mode_id' => $room['modes_id'], 'level_id' => $room['levels_id']
        ])->value('id');

        $tickets = (new Groups())->deduction($user_id, $group_id);//门票money 服务费service
        $all_tickets = $tickets['money'] + $tickets['service'];//总费用
        $user_money = User::where('id', $user_id)->value('money', 0);
        $user_gold = User::where('id', $user_id)->value('gold', 0);
        if ($user_money < $all_tickets) {//对比余额
            if ($user_gold < $all_tickets) {
                $params['user_id'] = $user_id;
                $params['currency_type'] = 2;
                $params['money'] = $tickets['money'];
                $params['service'] = $tickets['service'];

            } else {
                $this->error("当前用户余额不足");
            }
        } else {

            $params['user_id'] = $user_id;
            $params['currency_type'] = 1;
            $params['money'] = $tickets['money'];
            $params['service'] = $tickets['service'];
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            $user = User::get($user_id);
            if ($user && $all_tickets != 0) {//门票减额
                switch ($params['currency_type']) {
                    case 1:
                        $before = $user['money'];
                        $after = function_exists('bcadd') ? bcadd($user['money'], -$all_tickets, 2) : $user['money'] - $all_tickets;
                        $user->save(['money' => $after]);
                        MoneyLog::create([
                            "user_id" => $user['id'], "money" => -$all_tickets, 'before' => $before,
                            'after' => $after, "memo" => "金铲铲门票-房间:" . $room['id'], "type" => 2,
                            'room_id' => $room['id']
                        ]);
                        break;
                    case 2:
                        $before = $user['gold'];
                        $after = function_exists('bcadd') ? bcadd($user['gold'], -$all_tickets, 2) : $user['gold'] - $all_tickets;
                        $user->save(['gold' => $after]);
                        GoldLog::create([
                            "user_id" => $user['id'], "gold" => -$all_tickets, 'before' => $before,
                            'after' => $after, "memo" => "金铲铲门票-房间:" . $room['id'], "type" => 3,
                            'room_id' => $room['id']
                        ]);
                        break;
                }

            }

            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();
        $room = \app\common\model\room\Lists::get($list[0]['room_id']);
        if (in_array($room['status'], [2, 3])) {
            $this->error("当前房间已结束");
        }
        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $all = $item['money'] + $item['service'];
                $tuser = User::get($item['user_id']);

                switch ($item['currency_type']) {
                    case 1:
                        $before_t = $tuser['money'];
                        $after_t = function_exists('bcadd') ? bcadd($tuser['money'], $all, 2) : $tuser['money'] + $all;
                        $tuser->save(['money' => $after_t]);
                        MoneyLog::create([
                            "user_id" => $item['user_id'], "money" => $all, 'before' => $before_t,
                            'after' => $after_t, "memo" => "金铲铲门票退还-房间:" . $item['room_id'],
                            "room_id" => $item['room_id'], "type" => 3
                        ]);
                        break;
                    case 2:
                        $before_t = $tuser['gold'];
                        $after_t = function_exists('bcadd') ? bcadd($tuser['gold'], $all, 2) : $tuser['gold'] + $all;
                        $tuser->save(['gold' => $after_t]);
                        GoldLog::create([
                            "user_id" => $item['user_id'], "gold" => $all, 'before' => $before_t,
                            'after' => $after_t, "memo" => "金铲铲门票退还-房间:" . $item['room_id'],
                            "room_id" => $item['room_id'], "type" => 4
                        ]);
                        break;
                }
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
}
